package com.example.gobang.controller;

import com.example.gobang.mapper.UserMapper;
import com.example.gobang.model.User;
import com.example.gobang.tool.ConStant;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@ResponseBody
public class UserController {

    @Resource
    private UserMapper userMapper;

    @PostMapping("/registered")
    public Object registered(String username,String password){
        //存在插入失败的情况,设计数据表的时候指定了 username 不能重复
        //如果已经插入张三在插入一次张三就会存在插入失败的情况
        try{
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            userMapper.registered(user);
            return user;
        }catch (org.springframework.dao.DuplicateKeyException e){
            User user = new User();
            return user;
        }

    }

    @PostMapping("login")
    public Object login(String username, String password, HttpServletRequest request){

        User user = userMapper.login(username);
        if (user == null || !user.getPassword().equals(password)){
            //登陆失败
            return new User();
        }

        //参数为 true ,当会话存在,直接返回,会话不存在就创建一个 会话
        //参数为 false. 会话存在,就返回,不存在直接返回 null,就不创建
        HttpSession session = request.getSession(true);
        session.setAttribute(ConStant.KEY_SESSION,user);

        return user;
    }

    @GetMapping("/userquery")
    public Object userQuery(HttpServletRequest request){
        try{
            HttpSession session = request.getSession(false);
            User user =(User) session.getAttribute(ConStant.KEY_SESSION);
            //拿这个 user 对象,去数据库中找,找到最新的数据
            User newUser = userMapper.login(user.getUsername());
            return newUser;
        }catch (NullPointerException e){
            return new User();
        }


    }

}
